package com.algorithm;

import java.util.*;

/**
 * @author: sun.hongliang
 * @create: 2019/12/11 16:33
 */
public class LevelOrderTest {
    public static void main(String[] args) {
        WeakHashMap<String,String> weakHashMap = new WeakHashMap<>();
        weakHashMap.put("a","b");
    }

    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> result = new ArrayList<>();
        if (root == null) return result;
        LinkedList<TreeNode> linkedList = new LinkedList<>();
        linkedList.add(root);
        int lev = 0;
        while (!linkedList.isEmpty()) {
            result.add(new ArrayList<>());
            int size = linkedList.size();
            for (int i = 0; i < size; i++) {
                TreeNode poll = linkedList.remove();
                result.get(lev).add(poll.val);
                if (poll.left != null) {
                    linkedList.add(poll.left);
                }
                if (poll.right != null) {
                    linkedList.add(poll.right);
                }
            }
            lev++;
        }
        return result;
    }

    public List<List<Integer>> levelOrder2(TreeNode root) {
        List<List<Integer>> levels = new ArrayList<List<Integer>>();
        if (root == null) return levels;
        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        queue.add(root);
        int level = 0;
        while (!queue.isEmpty()) {
            levels.add(new ArrayList<Integer>());
            int level_length = queue.size();
            for (int i = 0; i < level_length; ++i) {
                TreeNode node = queue.remove();
                levels.get(level).add(node.val);
                if (node.left != null) queue.add(node.left);
                if (node.right != null) queue.add(node.right);
            }
            level++;
        }
        return levels;
    }
}
